package com.rjxy.plansystemmanagement.controller.login;

import com.rjxy.plansystemmanagement.entity.Result.Result;
import com.rjxy.plansystemmanagement.entity.User;
import com.rjxy.plansystemmanagement.service.UserService;
import com.rjxy.plansystemmanagement.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@Slf4j
@CrossOrigin
public class LoginController {
    @Autowired
    private UserService userService;

    @PostMapping("/login")
    public Result login(@RequestBody User user){
        log.info("用户登录{}",user);
        User u = userService.login(user);
        //登录成功下发令牌，里面包含用户的id，用户名和真实姓名
        if(u!=null){
            Map<String, Object> claims = new HashMap<>();
            claims.put("id",u.getID());
            claims.put("username",u.getUserName());
            claims.put("name",u.getName());
            String jwt = JwtUtils.generateJwt(claims);
            return Result.success(jwt);
        }
        return Result.error("用户名或密码错误");
    }
}
